<template>
  <el-upload
    v-if="isUpload"
    ref="elUpload"
    class="upload-demo"
    action="http://up-z0.qiniup.com"
    :data="qnFileData"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :limit="maxFileLength"
    :on-exceed="handleExceed"
    :before-upload="beforeAvatarUpload"
    :on-success="handleAvatarSuccess"
    :file-list="fileList"
  >
    <!-- multiple 多选 -->
    <el-button
      v-if="isUpload"
      size="small"
      type="primary"
    >点击上传</el-button>
  </el-upload>
  <span
    v-else
    class="file-list"
  >
    <template v-if="fileList.length>=1">
      <span
        class="file-item text-line-1"
        :class="[fileList.length>1?'lengthMore':'']"
      >
        <a
          :href="fileList[0].url"
          target="_blank"
        >{{ fileList[0].name }}</a>
      </span>
      <el-popover
        v-if="fileList.length>1"
        placement="top"
        trigger="hover"
        :width="300"
      >
        <template #reference>
          <span class="more-icon"><i class="iconfont icon-zhankai" /></span>
        </template>
        <div
          v-for="(item, idx) in fileList"
          :key="idx"
          style="padding: 5px 0px"
        >
          <a
            class="main-color"
            :href="item.url"
            target="_blank"
          >{{ item.name }}</a>
        </div>
      </el-popover>
    </template>
  </span>
</template>
<script>
import {ElMessage, ElMessageBox} from 'element-plus'
import api from '@CRM/api/index.js'
import {downloadFile} from '@/utils/downloadFile'

export default {
  name: 'Uploadele',
  props: {
    maxFileLength: { type: Number, default: 3 }, // 最大上传文件数量
    fileArr: { type: Array, default: () => [] },
    isUpload: { type: Boolean, default: true }, // 是否上传模式
    clsListBoolean: { type: Boolean }, // 是否清空
  },
  data() {
    return {
      QNSrcHeader: import.meta.env.VITE_CRM_QINIU_URL,
      qnFileData: {
        token: '',
      },
      fileDate: [],
      fileList: [],
      fileListSubmit: [], // 提交的数据
      FileType: '', // 文件类型
    }
  },
  watch: {
    clsListBoolean(newVal) {
      if (newVal) {
        this.fileList = []
        this.fileListSubmit = []
        this.$refs['elUpload']?.clearFiles()
        this.$emit('clsRefresh', false)
      }
    },
    fileArr(newVal) {
      if (this.fileArr && this.fileArr.length) {
        const fileList = []
        const fileSubmitList = []
        const fileListData = this.fileArr
        fileListData.forEach((item) => {
          const itemData = {
            name: item.name,
            url: item.url + '?attname=' + item.name,
          }
          const submitData = {
            name: item.name,
            url: item.url,
          }
          fileList.push(itemData)
          fileSubmitList.push(submitData)
        })
        this.fileList.splice(0, this.fileList.length, ...fileList)
        this.fileListSubmit = fileSubmitList
      } else {
        this.fileList.splice(0, this.fileList.length)
        this.fileListSubmit.splice(0, this.fileListSubmit.length)
        this.$refs['elUpload']?.clearFiles()
      }
    },
  },
  created() {
    console.log(this.fileArr)
    if (!this.fileArr) {
      this.fileArr = []
    }
    if (this.fileArr.length) {
      const fileList = []
      const fileSubmitList = []
      const fileListData = this.fileArr
      fileListData.forEach((item) => {
        const itemData = {
          name: item.name,
          url: item.url + '?attname=' + item.name,
        }
        const submitData = {
          name: item.name,
          url: item.url,
        }
        fileList.push(itemData)
        fileSubmitList.push(submitData)
      })
      this.fileList.splice(0, this.fileList.length, ...fileList)
      this.fileListSubmit = fileSubmitList
    }
  },
  methods: {
    handlePreview(file) {
      // 下载
      console.log(file)
      downloadFile(file.url)
    },
    handleRemove(file, fileList) {
      console.log(123)
      // 附件删除
      const fileListSubmit = this.fileListSubmit
      const fileNameList = fileListSubmit.map((item) => item.url)
      const spliceIndex = fileNameList.indexOf(file.name)
      fileListSubmit.splice(spliceIndex, 1)
      this.fileListSubmit = fileListSubmit
      this.fileList.splice(0, this.fileList.length, ...fileList)
      this.fileArr.splice(0, this.fileArr.length)
      for (var item of this.fileList) {
        this.fileArr.push({
          name: item.name,
          url: item.url.split('?')[0],
        })
      }
      // this.backDataMehods();
    },
    beforeRemove(file, fileList) {
      // 文件删除前确认

      return ElMessageBox.confirm(`确定移除 ${file.name}？`, {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        cancelButtonClass: 'cancelBtn',
        dangerouslyUseHTMLString: true,
        customClass: 'confrim-alter',
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })

      // return ElMessageBox.confirm(`确定移除 ${file.name}？`)
    },
    handleExceed(files, fileList) {
      ElMessage.warning(
        `当前限制选择 ${this.maxFileLength} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    handleAvatarSuccess(res, file) {
      this.fileList.push({
        name: this.FileType,
        url: this.QNSrcHeader + res.hash + '?attname=' + this.FileType,
      })
      this.fileListSubmit.push({
        url: this.QNSrcHeader + res.hash,
        name: this.FileType,
      })
      this.fileArr.splice(0, this.fileArr.length)
      for (var item of this.fileList) {
        this.fileArr.push({
          name: item.name,
          url: item.url.split('?')[0],
        })
      }
      // this.backDataMehods();
      console.log(this.fileArr)
    },
    QNTokenRequestFun() {
      return api.common.GET_QINIU_TOKEN().then((res) => {
        if (!res.code) this.qnFileData.token = res.data
      })
    },
    async beforeAvatarUpload(file) {
      // 文件上传前
      // this.qnFileData.name = file.name;
      var FileExt = file.name.replace(/.+\./, '')
      this.FileType = file.name
      this.fileDate = file
      await this.QNTokenRequestFun()
    },
    backDataMehods() {
      this.$emit('update:toFarUpload', this.fileListSubmit)
    },
  },
}
</script>
<style lang="scss" scoped>
@import "@/style/basics.scss";
.file-list {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .file-item {
    display: inline-block;
    color: $main-color;
    a {
      color: $main-color;
    }
    &.lengthMore {
      max-width: 80%;
    }
  }
  .more-icon {
    font-size: 14px;
    color: $main-color;
    margin-left: 5px;
  }
  .file-item:last-child {
    padding-bottom: 0;
  }
}
</style>
